//
//  ProtocolViewController.m
//  Cycling
//
//  Created by cjg.mini on 2023/4/25.
//

#import "ProtocolViewController.h"
#import "WKWebViewJavascriptBridge.h"


@interface ProtocolViewController ()<WKNavigationDelegate>
@property (nonatomic, strong) WKWebView* webView;
@property WKWebViewJavascriptBridge* bridge;

@end

@implementation ProtocolViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (_bridge) { return; }
    WKWebView* webView = [[NSClassFromString(@"WKWebView") alloc] initWithFrame:self.view.bounds];
    [webView setOpaque:NO];
    webView.navigationDelegate = self;
    webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self loadExamplePage:webView];

    [self.view addSubview:webView];
    
    [WKWebViewJavascriptBridge enableLogging];
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView];
    [_bridge setWebViewDelegate:self];

    [_bridge registerHandler:@"onBackPress" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= onBackPress");

        [self.navigationController popViewControllerAnimated:YES];
    }];
    // js调用oc传状态栏高度
    [_bridge registerHandler:@"getTopHeight" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSString *height = [NSString stringWithFormat:@"%f",SafeAreaTopHeight];
        responseCallback(@{@"height":height});
    }];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];

}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"webViewDidStartLoad");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"webViewDidFinishLoad");
}

- (void)loadExamplePage:(WKWebView*)webView {
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.htmlStr]]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

@end
